<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" @filterChange="changeHandler" @onCollapse="collapseHandle" />
    <FilterTable
      ref="table"
      columnsRef="maintenanceBoutique"
      :columns="columns"
      selectionType="single"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
    >
      <template slot="controls">
        <AjaxButton :click="viewDetails" type="primary">查看明细</AjaxButton>
        <AjaxButton :click="printOrder" type="primary">补打派工单</AjaxButton>
        <AjaxButton :click="printClearCountOrder" type="primary">补打派工结算单</AjaxButton>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Details :queryParams="queryParams" @closeDialog="closeDialog" />
    </BaseDialog>

    <!-- 补打派工单 -->
    <BasePrint ref="workOrderPrint" :data="workOrderPrintData" template="boutique/report/maintenanceBoutiqueSelect/templateWorkOrder" />
    <!-- 补打派工结算单 -->
    <BasePrint ref="workOrderPrintClearCount" :data="workOrderClearCountPrintData" template="boutique/report/maintenanceBoutiqueSelect/templateWorkOrderClearCount" />
  </div>
</template>

<script>
/**
 * 查询装饰派工单项目报表
 */
// 数据字典/按钮权限
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { confirmAction, notifyAction } from '@/utils';
import { getAllUser, queryCompanyInforById } from '@/api/part/common';
import { getOrderList, getWorkPrint, getWorkClearPrint } from '@/api/part/qualityManagement/report';
import Details from './inquiryForDecorationOrders/details';
import { getUser, getCompanyId } from '@/assets/js/auth';

export default {
  name: 'CardType',
  components: { Details },
  mixins: [dictionary, authority],
  data() {
    this.BaseTable = null;
    this.selectedRow = null;
    this.editData = {};
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getOrderList,
      fetchParams: {},
      actions: { visible: false, type: '', title: '' }, // 弹出面板的相关信息,
      isChoice: true, // 按钮是否可以选择
      userList: [], // 人员列表
      selectColumns: [],
      visible: false, // 弹窗是否显示
      dialogTitle: '明细',
      queryParams: {}, // 查询条件
      workOrderPrintData: {}, // 补打派工单打印数据
      workOrderClearCountPrintData: {} // 补打派工结算单打印数据
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    // 打印派工单
    async printOrder() {
      if (this.selectColumns.length < 1) {
        return this.$notify.error({ title: '提示信息', message: '请选中一条数据' });
      }

      let res = await getWorkPrint({ workId: this.selectColumns[0].workId });
      console.log('打印数据', res.data);
      if (res.resultCode == 200) {
        res.data.user = getUser();
        this.workOrderPrintData = res.data;
        this.$refs.workOrderPrint.EXCUTE_PRINT();
      }
    },
    // 打印派工结算单
    async printClearCountOrder() {
      if (this.selectColumns.length < 1) {
        return this.$notify.error({ title: '提示信息', message: '请选中一条数据' });
      }

      if (this.selectColumns.length && this.selectColumns[0].settlementStatus == 10041002) {
        return this.$notify.error({ title: '提示信息', message: '订单未结算不能打印' });
      }

      let res = await getWorkClearPrint({ workId: this.selectColumns[0].workId });
      if (res.resultCode == 200) {
        let compinyInfo = {};
        try {
          compinyInfo = (
            await queryCompanyInforById({
              owenrCode: getCompanyId()
            })
          ).data;
        } catch (err) {
          console.log(err, '获取公司信息失败');
        }
        res.data.user = getUser();
        res.data.compinyInfo = compinyInfo;
        res.data.fourthTable.balanceModeName = this.createDictText(res.data.fourthTable.balanceModeCode, '8044') || res.data.fourthTable.balanceModeCode;
        this.workOrderClearCountPrintData = res.data;
        this.$refs.workOrderPrintClearCount.EXCUTE_PRINT();
      }
    },
    // 关闭弹窗
    closeDialog() {
      this.visible = false;
    },
    // 查看明细
    viewDetails() {
      if (this.selectColumns.length < 1) {
        return this.$notify.error({ title: '提示信息', message: '请选中一条数据' });
      }
      this.queryParams = this.selectColumns[0];
      this.visible = true;
    },
    // 获取所有人员信息
    async getUsers() {
      let res = await getAllUser();
      if (res.resultCode == 200) {
        res.data.map(e => {
          this.userList[e.userId] = e.employeeName;
        });
      }
    },
    createTopFilters() {
      return [
        {
          type: 'RANGE_DATE',
          label: '派工日期',
          dateType: 'daterange',
          style: { minWidth: '120px' },
          fieldName: 'orderDateBegin|orderDateEnd'
        },
        {
          type: 'RANGE_DATE',
          label: '结算日期',
          dateType: 'daterange',
          style: { minWidth: '120px' },
          fieldName: 'balanceDateBegin|balanceDateEnd'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '装饰派工单号',
          dataIndex: 'billNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户代码',
          dataIndex: 'customerNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '牌照号',
          dataIndex: 'licenseTag',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '派工时间',
          dataIndex: 'orderDate',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '工时费金额',
          dataIndex: 'boutiqueItemCostSum',
          sorter: true,
          filter: true,
          filterType: 'number',
          summation: true,
          precision: 2
        },
        {
          title: '装饰件金额',
          dataIndex: 'boutiquePartCostSum',
          sorter: true,
          filter: true,
          filterType: 'number',
          summation: true,
          precision: 2
        },
        {
          title: '合计金额',
          dataIndex: 'receiveAmount',
          sorter: true,
          filter: true,
          filterType: 'number',
          summation: true,
          precision: 2
        },
        {
          title: '其他费用',
          dataIndex: 'otherAmount',
          sorter: true,
          filter: true,
          filterType: 'number',
          summation: true,
          precision: 2
        },
        {
          title: '优惠金额',
          dataIndex: 'totalDiscountAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '实收金额',
          dataIndex: 'receiveAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '整车销售单号',
          dataIndex: 'saleOrderNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '会员卡号',
          width: 145,
          dataIndex: 'cardNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'remarks',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '整车销售单号',
        //   dataIndex: 'o',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '结算状态',
          dataIndex: 'settlementStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.settlementStatus, '1004')}</span>;
          }
        },
        {
          title: '结算日期',
          dataIndex: 'balanceTime',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '结算人',
          dataIndex: 'balanceHandler',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.balanceHandler]}</span>;
          }
        },
        {
          title: '操作员',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.createdBy]}</span>;
          }
        },
        {
          title: '完工审核',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('9704'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '9704')}</span>;
          }
        },
        {
          title: '审核日期',
          dataIndex: 'reviewDate',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        }
      ];
    },
    addRecordHandle() {
      this.actions = { visible: true, type: 'add', title: '新增精品项目' };
    },
    editRecordHandle(row) {
      if (!row) return;
      this.editData = row;
      this.actions = { visible: true, type: 'edit', title: '编辑精品项目' };
    },
    changeHandler(val) {
      this.fetchParams = { ...val };
    },
    rowSelectHandle(rows) {
      if (!rows.length) return;
      console.log(rows[0]);
      this.selectedRow = rows[0];
    },
    // 移除数据记录
    async removeRecordHandle() {
      try {
        await confirmAction('此操作将删除该记录, 是否继续?');
        const res = await doRemove({ id: this.selectedRow.id });
        if (res.resultCode === 200) {
          notifyAction('删除数据成功！');
          // 执行刷新
          this.refreshHandle();
        }
      } catch (e) {}
    },
    // 主页面刷新
    refreshHandle() {
      this.fetchParams = { ...this.fetchParams };
    },
    // 操作面板关闭
    closeActionPanel(val, type) {
      this.actions.visible = val;
      // 重置 editData
      this.editData = {};
      // 执行刷新
      type === 'refresh' && this.refreshHandle();
    },
    // 适配 BaseTable 组件
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    }
  }
  // ,
  // mounted() {
  //   this.BaseTable = this.$refs.table.$refs.pageTable;
  // }
};
</script>

<style lang="less" scoped></style>
